<?php


namespace App\Controllers;


use App\Models\BotModel;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Controller;
use Phpanalysis\Phpanalysis;

class Interflow extends Controller
{
    use ResponseTrait;

    public function __construct()
    {
        helper('bot');
    }

    /**
     * @title 发送消息
     * @param port :int :端口
     * @param account :string :账号
     * @param message :string :消息
     * @return \json
     */
    public function send_private_msg()
    {
        $validation = \Config\Services::validation();
        $params = $this->request->getPost();
        if (!$validation->run($params, 'port')) {
            return $this->failValidationErrors(implode('\\', array_values($validation->getErrors())));
        }
        try {
            $res = send_private_msg($params);
        } catch (\Exception $p) {
            $msg = str_replace(masking_dir(), masking_replace(), $p->getMessage());
            return $this->fail($msg, 400);
        }

        $res_data = [
            'data' => json_decode($res, true),
            'status' => 200,
        ];
        return $this->respondCreated($res_data);
    }

    /**
     * @title 详细推送地址
     */
    public function push_notify()
    {
        $content = file_get_contents("php://input");

        $response = json_decode($content, true);
        if (isset($response['message_type'])) {
            if ($response['message_type'] == 'private') {
                #拆分
                $pals = new Phpanalysis('utf-8', 'utf-8', true);
                $pals->LoadDict();
                $pals->SetSource($response['message']);
                $pals->differMax = true;
                $pals->unitWord = true;
                $pals->differFreq = true;
                $pals->SetResultType(2);
                $pals->StartAnalysis( true);
                $keywords = $pals->GetFinallyResult();

                $opts = [
                    'device' => 'Qq',
                    'account' => (string)$response['self_id'],
                    'sender' => (string)$response['sender']['user_id'],
                    'message' => (string)$response['message'],
                    'message_keywords' => (string)$keywords,
                ];
                $opts['sign'] = openssl_encrypt((md5(json_encode($opts))), 'AES-128-ECB', '77688beae9fb9282af1d39e580a492fa', 0, '');
                push_notify($response['self_id'], $opts);
                log_message('error', json_encode($opts));
            }
        }

        exit('success');
    }

}